
/**
 * 中心评分表
 * @author wl
 */
import React, {useRef, useState, useEffect} from 'react';
import {Card, Button, Modal} from 'antd';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import CommonCard from '~/page/FineBi/common/CommonCard';
import Loading from '~/page/FineBi/common/Loading';
import CommonTitle from '~/page/FineBi/common/Title';
import {convertSearcherParams} from '~/page/FineBi/utils/convert';
import {
    querySelectOptions,
    queryValues,
    download,
    querySelectOptions1,
    queryCentralValues
} from '~/service/refundReport';
import BarItem from './comps/BarItem';
import TableAll from './comps/TableAll';
import TableItem from './comps/TableItem';


import {
    filterTypeKey,
    initialValues,
    searchConfig as allSearchConfig,
    initSearchConfig,
    periedKey,
    partConfig,
    tableConfig,
    COMMON_KEY,
} from './config';

import './style.styl';

const WinterStudent = props => {
    const formRef = useRef();
    const [selectOptions, setSelectOptions] = useState({});
    const [loading, setLoading] = useState(false);
    const [pictureUrl, setPicture] = useState();
    const [title, setTitle] = useState();
    const [dimensionAndValues, setDimensionAndValues] = useState([]);
    const [searchConfig, setSearchConfig] = useState(initSearchConfig);
    const [curFilterType, setCurFilterType] = useState(initialValues[filterTypeKey]);
    const [loadingInitSearch, setLoadingInitSearch] = useState(true);
    const [isDownloading, setIsDownloading] = useState(false);
    const [modalVisibel, setModalVisibel] = useState(false);

    const handleOk = fieldsValue => {
        // 这个 filterTypeKey 过滤器只是控制筛选器的状态
        delete fieldsValue[filterTypeKey];

        const params = convertSearcherParams(fieldsValue);
        setDimensionAndValues(params);
    };

    const handleReset = e => {
        setDimensionAndValues([]);
        setSearchConfig(initSearchConfig);
        setCurFilterType(initialValues[filterTypeKey]);
    };

    // 选项查询
    const handleFetchOptions = options => {
        const {key, searchKey, pager, isGetingMore, options: curOptions, fieldsValue, optionsConfig} = options;

        if (key === filterTypeKey) {
            setSelectOptions({key, options: curOptions, pager});
            return;
        }

        const params = {
            pager,
            dimensionId: `${optionsConfig.unitId}_${key}`,
            dimensionName: key,
            searchKey,
            permissions: [],
            unitId: optionsConfig.unitId
        };

        // 期的接口和其他的不同
        const fetchFn = key === periedKey ? querySelectOptions1 : querySelectOptions;

        return fetchFn(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});

            return (data || []);
        });
    };

    const handleDownload = () => {
        const pDimensionAndValues = dimensionAndValues.map(item => ({
            ...item,
            dimensionId: `CentralScoring_Download_PartOne_excel_${COMMON_KEY}`,
            dimensionName: COMMON_KEY
        }));

        const params = {
            unitId: 'CentralScoring_Download_PartOne_excel',
            dimensionAndValues: pDimensionAndValues
        };
        const excelName = '';
        setIsDownloading(true);
        download(params, excelName, () => setIsDownloading(false));
    };

    const handleItemChange = formItem => {
        if (formItem[filterTypeKey]) {
            const result = allSearchConfig.filter(configItem =>
                (configItem.key === filterTypeKey || configItem.key === formItem[filterTypeKey]));

            setSearchConfig(result);
            setCurFilterType(formItem[filterTypeKey]);
        }
    };

    useEffect(() => {
        const dashBoard = [
            {
                dashBoardName: 'CentralScoring_Title',
                dashBoardId: 'CentralScoring_Title'
            }
        ];
        const param = {
            dimensionAndValues,
            dashBoardList: dashBoard
        };
        setLoading(true);
        queryValues(param)
            .then(res => {
                const {unitName, pictureUrl} =
                    res?.data?.CentralScoring_Title?.CentralScoring_Title_picture ?? null;
                if (pictureUrl) {
                    setPicture(pictureUrl);
                    setTitle(unitName);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    // 每次切换筛选配置时，需要手动赋默认值
    useEffect(() => {
        const form = formRef.current?.formFields;
        const curFilterValue = form?.getFieldValue(curFilterType);

        if (!curFilterValue) {
            setLoadingInitSearch(true);
            const curSearchConfig = allSearchConfig.find(item => item.key === curFilterType);
            Promise.all([handleFetchOptions(curSearchConfig)])
                .then(res => {
                    const data = res?.[0] || [];
                    const obj = {
                        // 如果是期，默认优先选第四个（分析师随便取的一个，应该有数据），如果是月份，默认选第一个
                        [curFilterType]: curFilterType === periedKey ? (data[3] || data[0]) : data[0]
                    };

                    form?.setFieldsValue(obj);

                    const params = convertSearcherParams(obj);
                    setDimensionAndValues(params);
                })
                .finally(() => {
                    setLoadingInitSearch(false);
                });
        }
    }, [curFilterType]);

    const handleModalVisible = bool => param => {
        setModalVisibel(bool);
    };


    return (
        <div className="center-score">
            <CommonTitle
                title="中心评分表"
                // remark="数据说明：转化率归一评分取订单维度综合转化率，订单维度综合转化率不包含转介绍，不含淘金，赠课，辅导代班，正转正数据"
            />
            <CommonTitle
                type="subTitle"
                title="1、行课历"
            />
            <Card style={{width: '100%'}}>
                <Loading loading={loading}>
                    <img width="100%" src={pictureUrl} alt="行课例" />
                </Loading>
            </Card>
            <CommonTitle
                type="subTitle"
                title="2、评分结果"
                iconDom={(
                    <span className="modal" onClick={handleModalVisible(true)}>
                        评分规则
                    </span>
                )}
                remark="说明：评分取订单维度数据，因此不含转介绍；不含辅导带班，正转正测试，单科测试，淘金，高中赠课"
            />

            <Card style={{width: '100%'}}>
                <CommonSearchBar
                    noCache
                    config={searchConfig}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    onItemChange={handleItemChange}
                    selectOptions={selectOptions}
                    ref={formRef}
                />
            </Card>
            {partConfig.map(item => (
                <>
                    <CommonTitle
                        type="subTitle"
                        title={`${item.num}、${item.title}`}
                    />
                    <Card>
                        {!loadingInitSearch && (
                            <div style={{display: 'flex', flexWrap: 'wrap'}}>
                                {item.parts.map(child => (
                                    <BarItem
                                        key={child.id}
                                        partKey={`${child.id}_bar`}
                                        dId={child.id}
                                        dimensionAndValues={dimensionAndValues}
                                        /* eslint-disable */
                                        // 期条件下，全量图的 接口跟其他的不一样
                                        queryCentralValues={curFilterType === periedKey && child.ajax && queryCentralValues}
                                    />
                                ))}
                            </div>
                        )}
                    </Card>
                </>
            ))}
            <CommonTitle
                title="III、板块诊断"
                type="subTitle"
                remark="说明：展示一个中心下每个学部流量占比超过2%的主讲中，综合转化率排名前2后2的数据展示；底色是深色的数据为TOP2主讲"
            />
            <Card>
                {!loadingInitSearch && (
                    <div style={{display: 'flex', flexWrap: 'wrap'}}>
                        <TableAll dimensionAndValues={dimensionAndValues} />
                        {tableConfig.map(item => (
                            <TableItem
                                key={item.id}
                                dId={item.id}
                                label={item.title}
                                // 期 是1 月份是2
                                searchType={curFilterType === periedKey ? 1 : 2}
                                dimensionAndValues={dimensionAndValues}
                            />
                        ))}
                    </div>
                )}
            </Card>
            <CommonTitle
                type="subTitle"
                title="3、数据下载"
                remark="数据说明：下载内容为分中心下所有主讲的订单量占比，转化率评分，人均产能评分和中心学部人均带班量；分中心负责人权限仅能下载本中心数据"
            />
            <Card style={{width: '100%'}}>
                <Button type="primary" onClick={handleDownload} loading={isDownloading}>
                    数据明细下载
                </Button>
            </Card>
            <Modal
                visible={modalVisibel}
                onCancel={handleModalVisible(false)}
                footer={null}
            >
                综合转化率归一评分规则 <br />
                1.计算各主讲在各一级渠道综合转化率作为归一基准 <br />
                2.计算各中心中主讲渠道细分综合转化率，并除以各细分模块对应基准值，得到中心细分模块对应归一评分 <br />
                3.计算各中心中主讲渠道细分模块流量占比，并乘以对应模块归一评分，得到中心整体归一评分 <br />
                <br />
                <br />
                人均产能归一评分规则 <br />
                1.计算各主讲在各一级渠道单效作为归一基准 <br />
                2.计算各中心中主讲渠道细分单效，并除以各细分模块对应基准值，得到中心细分模块对应归一评分 <br />
                3.计算各中心中主讲渠道细分模块流量占比，并乘以对应模块归一评分，得到中心整体单效归一评分 <br />
                4.计算各中心学部的人均带班量除以学部人均带班量，得到中心人均带班量归一评分 <br />
                5.单效归一评分乘以人均带班量归一评分得出人均产能归一评分 <br />
                <br />
                <br />
                最终评分展示 <br />
                综合转化率归一评分和人均产能归一评分均进行三次方并乘以100的运算
            </Modal>
        </div>
    );
};

export default WinterStudent;
